import { createRouter, createWebHistory } from 'vue-router'

const routes = [
  {
    path: '/',
    redirect: '/dashboard'
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
    meta: { requiresGuest: true }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/Register.vue'),
    meta: { requiresGuest: true }
  },
  {
    path: '/dashboard',
    name: 'Dashboard',
    component: () => import('@/views/Dashboard.vue'),
    meta: { requiresAuth: true }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 直接从localStorage检查token，避免Pinia初始化问题
  const token = localStorage.getItem('token')
  const isLoggedIn = !!token
  
  console.log('🛡️ =================================')
  console.log('🛡️ 路由守卫检查')
  console.log('🛡️ 从:', from.path)
  console.log('🛡️ 到:', to.path)
  console.log('🛡️ Token存在:', !!token)
  console.log('🛡️ Token长度:', token ? token.length : 0)
  console.log('🛡️ 需要认证:', to.matched.some(record => record.meta.requiresAuth))
  console.log('🛡️ 游客页面:', to.matched.some(record => record.meta.requiresGuest))
  
  // 需要登录的页面
  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!isLoggedIn) {
      console.log('❌ 需要登录但未登录，跳转到登录页面')
      next('/login')
      return
    } else {
      console.log('✅ 已登录，允许访问')
    }
  }
  
  // 游客页面（登录、注册）
  if (to.matched.some(record => record.meta.requiresGuest)) {
    if (isLoggedIn) {
      console.log('🔄 已登录用户访问游客页面，跳转到首页')
      next('/dashboard')
      return
    } else {
      console.log('✅ 未登录用户访问游客页面，允许访问')
    }
  }
  
  console.log('✅ 路由守卫通过，继续导航')
  console.log('🛡️ =================================')
  next()
})

export default router